package com.ww.grtsmanager.service.impl;


import com.ww.grtsmanager.bean.Subject;
import com.ww.grtsmanager.mapper.SubjectMapper;
import com.ww.grtsmanager.service.SubjectService;
import com.ww.grtsmanager.vo.SubjectTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectMapper subjectMapper;


    @Override
    public List<SubjectTree> getSubjectTree() {
        List<SubjectTree> list = getSubjectTreeAll(0);
        return list;
    }

    @Override
    public void addSubject(Subject subject) {
        if (StringUtils.isBlank(subject.getTitle())){
            throw new RuntimeException("课程分类名称不能为空");
        }
        //查询到有这个一级类目再做添加
        Subject s = subjectMapper.getSubjectById(subject.getParentId());
        if (s==null){
            throw new RuntimeException("该一级分类已被删除，请刷新页面");
        }
        Date date = new Date();
        subject.setGmtCreated(date);
        subject.setGmtModified(date);
        int i = subjectMapper.addSubject(subject);
        if (i==0){
            throw new RuntimeException("添加课程分类失败");
        }
    }

    @Transactional//mysql的事务管理 作用是让sql语句同时失败（回滚到最初）或同时成功
    @Override
    public void deleteSubject(Integer id) {
        /**
         * 页面只会传一个id 不知道是一级分类id还是二级分类id
         * 1、删除自身 2、删除其子集
         */
        int i = subjectMapper.deleteSubjectByParentId(id);
        int j = subjectMapper.deleteSubjectById(id);
        if (j==0){
            throw new RuntimeException("该分类已被删除，请刷新页面");
        }
    }

    //我们自己创建了一个方法，作用是获取所有课程分类数据
    public List<SubjectTree> getSubjectTreeAll(int parentId){
        List<SubjectTree> list = new ArrayList<SubjectTree>();
        //因为丢的是0 所以现在查的是一级类目
        List<Subject> subjectList = subjectMapper.getSubjectByParentId(parentId);
        if (subjectList!=null){
            for (Subject subject:subjectList) {
                SubjectTree tree = new SubjectTree();
                tree.setId(subject.getId());
                tree.setLabel(subject.getTitle());
                tree.setParentId(subject.getParentId());
                //自己调用自己
                List<SubjectTree> treeList = getSubjectTreeAll(tree.getId());
                if (treeList.isEmpty()){
                    tree.setChildren(null);
                }else {
                    tree.setChildren(treeList);
                }
                list.add(tree);
            }
        }

        return list;
    }
}
